import { IMenu, IUserInfo } from '@/api/types/common'
import { USER, MENU } from '@/utils/constants'
import { getItem, setItem } from '@/utils/storage'
import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'

// 为 store state 声明类型
const state = {
  user: getItem<{ token: string } & IUserInfo>(USER),
  menus: getItem<IMenu[]>(MENU) || []
}

export type State = typeof state

// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol('InjectionKey')

// 创建一个新的 store 实例
const store = createStore<State>({
  state,
  mutations: {
    setUser (state, payload) {
      state.user = payload
      setItem(USER, payload)
    },
    setMenus (state, payload) {
      state.menus = payload
      setItem(MENU, payload)
    }
  }
})

// 定义自己的 `useStore` 组合式函数
export function useStore () {
  return baseUseStore(key)
}

export default store
